import pool from '../db'
import c from 'crypto'

export default defineEventHandler(async (event) => {
  const body = await readBody(event)
  const { username, password, confirmPassword } = body

  if (password !== confirmPassword) {
    throw createError({
      statusCode: 400,
      statusMessage: '注册失败',
      message: '两次输入的密码不一致'
    })
  }

  try {
    const connection = await pool.getConnection()

    // 检查用户名是否已存在
    const [rows] = await connection.execute(
      'SELECT * FROM users WHERE username = ?',
      [username]
    )

    if (Array.isArray(rows) && rows.length > 0) {
      throw createError({
        statusCode: 400,
        statusMessage: '注册失败',
        message: '用户名已存在'
      })
    }

    // 密码哈希
    const salt = c.randomBytes(4).toString('base64')
    const hash = c
      .pbkdf2Sync(password, salt, 1000, 18, 'sha256')
      .toString('hex')

    // 创建用户
    await connection.execute(
      'INSERT INTO users (username, password,salt) VALUES (?, ?,?)',
      [username, hash, salt]
    )

    return {
      code: 200,
      statusMessage: '注册成功',
      message: '注册成功'
    }
  } catch (error: any) {
    if (error?.statusCode === 400) {
      throw error
    }

    throw createError({
      statusCode: 500,
      statusMessage: '注册失败',
      message: error.message
    })
  }
})
